package com.azdebugit.trancation.test;

import com.azdebugit.trancation.test.enu.DictCodeKeyEnum;
import com.azdebugit.trancation.test.handler.MessageReminderHandler;
import com.azdebugit.trancation.test.pojo.DingDingMsgVO;
import com.azdebugit.trancation.test.pojo.UtilDictKVEntity;
import com.azdebugit.trancation.test.service.CompensationService;
import com.azdebugit.trancation.test.service.UtilDictKVService;
import com.azdebugit.trancation.test.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;

//定时任务类
@Component
public class CompensateDataSchedulerTask {
    private static final Logger logger = LoggerFactory.getLogger(CompensateDataSchedulerTask.class);
    @Resource
    CompensationService compensationService;
    @Resource
    MessageReminderHandler messageReminderHandler;
    @Autowired
    private UtilDictKVService utilDictKVService;

    public final static String INTERFACE_NAME = "通用补偿接口";

    /**
     * 1: 任务只重试status=0的
     * 每隔5分钟一次，每次每条记录重试1次
     * tip:
     * 因为考虑到 定时任务是5分钟跑一次，所以数据量不会很大，因此，
     * 我们不用异步和线程池处理了。就同步处理。数据也同步更新到数据库。
     * 后期有改造，再进行优化
     * <p>
     * 考虑到线上有多台机器。我们默认指定一台机器进行运行。
     */
    @Scheduled(initialDelay = 10000, fixedDelay = 300000)
    public void retry() {
        if (exeScheduledIP()) {
            logger.info("开始进行补偿！");
            String dealResult = compensationService.autoRetry();
            logger.info(dealResult);
        }
    }

    /**
     * 钉钉提醒：失败待补偿的钉钉提醒。
     * 每天上午10:15触发
     */
    @Scheduled(cron = "0 15 10 ? * *")
    public void dingDingCompensationRemind() {
        if (exeScheduledIP()) {
            // 获取需要发送的 内容
            String env = messageReminderHandler.getEnv();
            String remindStr = compensationService.analysisData();
            String dingDingMsgVO = messageReminderHandler.buildDingDingMsgVO(INTERFACE_NAME, "环境：" + env + "!" + remindStr, DictCodeKeyEnum.DING_DING_COMPENSATE_MOBILE.getMsg());
            String sendResult = messageReminderHandler.dingDingSend(DictCodeKeyEnum.DING_DING_COMPENSATE_URL.getMsg(), dingDingMsgVO);
            logger.info("CompensateDataSchedulerTask->dingDingRemind->sendResult:" + sendResult);
        }
    }


    /**
     * 是否可以执行定时任务
     *
     * @return true/false
     */
    private Boolean exeScheduledIP() {
        UtilDictKVEntity utilDictKVEntity = utilDictKVService.getKvsByDictCodeKey(DictCodeKeyEnum.CURRENT_COMPENSATE_IP.getCode(), DictCodeKeyEnum.CURRENT_COMPENSATE_IP.getMsg(), 3600L);
        ValidateUtils.notNull("utilDictKVEntity", "未配置执行定时任务的");
        String localIp = null;
        try {
            InetAddress ia = InetAddress.getLocalHost();
            localIp = ia.getHostAddress();
        } catch (UnknownHostException e) {
            logger.error(e.getMessage(), e);
            return false;
        }
        return localIp.equals(utilDictKVEntity.getDictValue());
    }

}